package com.cazor.dgjq.app;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cazor.dgjq.domain.DgjqDeviceSensor;
import com.cazor.dgjq.domain.DgjqHisDataReqList;
import com.cazor.dgjq.domain.DgjqParamDataSensor;
import com.cazor.dgjq.service.DgJqCommonService;
import com.cazor.dgjq.service.IDgjqParamDataSensorService;
import com.cazor.mg.domain.MgDeviceGroup;
import com.cazor.mg.domain.MgParamLog;
import com.cazor.mg.service.IMgParamLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DgJqAppService {

    @Resource
    DgJqCommonService dgJqCommonService;
    @Resource
    private IDgjqParamDataSensorService dgjqParamDataSensorService;

    @Resource
    private IMgParamLogService mgParamLogService;
    @Resource
    private DgjqAppReqService dgjqAppReqService;

    public void monitorSensorStatus(){



    }


    /**
     * 传感器实时数据上报接口
     */
    public void monitorSensorData(){

        Map<String, DgjqParamDataSensor> paramDataSensorMap = getParamDataSensorMap();

        // 地震仪数据列表
        List<DgjqDeviceSensor> list = dgJqCommonService.getSensorList("地震烈度");

        // GNSS地表位移 列表
        list = dgJqCommonService.getSensorList("GNSS地表位移");

        // 传感器数据列表
        list = dgJqCommonService.getSensorList("管道应变");




    }

    private void getSensorData(List<DgjqDeviceSensor> list, Map<String, DgjqParamDataSensor> paramDataSensorMap){
        int size = CollectionUtil.size(list);
        if (size > 0) {
            String sensorId = null;
            DgjqParamDataSensor paramDataSensor = null;
            List<MgParamLog> paramLogList = null;
            for (DgjqDeviceSensor deviceSensor : list) {
                sensorId = deviceSensor.getSensorId();
                paramDataSensor = paramDataSensorMap.get(sensorId);
                if (paramDataSensor == null || paramDataSensor.getUpdateTime() == null){
                    log.warn("sensorId({}) / maxReadDate({}) 为空 不能查询"
                            , sensorId
                            , paramDataSensor.getUpdateTime()==null?"null":DateTime.of(paramDataSensor.getUpdateTime()).toString(DatePattern.NORM_DATETIME_PATTERN));
                    continue;
                }
                paramLogList = this.getMgParamLog(sensorId, paramDataSensor.getUpdateTime());
                int count = CollectionUtil.size(paramLogList);
                if (count > 0) {
                    // 排序
                    paramLogList = paramLogList.stream()
                            .sorted(Comparator.comparing(MgParamLog::getReadDate)).collect(Collectors.toList());


                }

            }
        }


    }


    private void sendSensorList(List<MgParamLog> paramLogList, DgjqDeviceSensor deviceSensor) {
        int count = CollectionUtil.size(paramLogList);
        if (count > 0) {
            JSONObject contentJson = null, jsonInfo = null, respJson = null;
            List<DgjqHisDataReqList> reqLists = new ArrayList<>();
            for (MgParamLog mgParamLog : paramLogList) {
                contentJson = this.initContentJson(mgParamLog, deviceSensor);

                respJson = dgjqAppReqService.sendSensorData(contentJson);
                this.sendSensorData(mgParamLog.getParentCode(), contentJson, respJson, reqLists);
            }

        }
    }

    public JSONObject initContentJson(MgParamLog mgParamLog, DgjqDeviceSensor deviceSensor) {
        JSONObject contentJson = new JSONObject(),jsonInfo = null;
        contentJson.put("device_id", deviceSensor.getSensorId());
        contentJson.put("device_name", deviceSensor.getName());
        contentJson.put("read_date", DateTime.of(mgParamLog.getReadDate()).toString(DatePattern.NORM_DATETIME_PATTERN));
        jsonInfo = JSON.parseObject(mgParamLog.getJsonInfo());
        jsonInfo.put("offline", "0");
        contentJson.put("json_info", jsonInfo);
        contentJson.put("timestamp", System.currentTimeMillis());
        return contentJson;
    }


    private void sendSensorData(String sensorId, JSONObject contentJson, JSONObject respJson,  List<DgjqHisDataReqList> reqLists) {
        if (reqLists == null) {
            return ;
        }
        DgjqHisDataReqList dataReq = new DgjqHisDataReqList();
        dataReq.setSensorId(sensorId);
        dataReq.setReq(contentJson.toString());
        dataReq.setCreateBy("sys");
        dataReq.setCreateTime(DateTime.now());
        if (respJson == null) {
            dataReq.setCode(401);
            dataReq.setSuccess("0");
        } else {
            JSONObject respContentJson = respJson.getJSONObject("contentJson");
            dataReq.setResp(respJson.toString());
            if (respContentJson == null || respContentJson.size() <= 0) {
                dataReq.setCode(501);
                dataReq.setSuccess("0");
            } else {
                dataReq.setCode(502);
                dataReq.setSuccess("0");
            }
        }
        if ("0".equals(dataReq.getSuccess())){
            reqLists.add(dataReq);
        }
    }

    /**
     * 截面数据上报接口
     */
    public void monitorSensorGroupData(){

        List<MgDeviceGroup> groupList = dgJqCommonService.getGroupList();
        int size = CollectionUtil.size(groupList);
        if (size > 0) {


        }

    }

//    private void validateRespJson(JSONObject respJson, )

    /**
     *
     * @return
     */
    public Map<String, DgjqParamDataSensor> getParamDataSensorMap(){
        List<DgjqParamDataSensor> paramDataSensorList =
                dgjqParamDataSensorService.list();

        Map<String, DgjqParamDataSensor> paramDataSensorMap = new HashMap<String, DgjqParamDataSensor>();
        if (CollectionUtil.isNotEmpty(paramDataSensorList)) {
            paramDataSensorMap = paramDataSensorList.stream()
                    .collect(Collectors.toMap(DgjqParamDataSensor::getSensorId, item -> item));
        } else {
            paramDataSensorMap = new HashMap<String, DgjqParamDataSensor>();
        }
        return paramDataSensorMap;
    }


    /**
     * 获取 某个传感器(sensorId) 大于某时间(maxReadDate) 的所有记录数据
     * @param sensorId 传感器id
     * @param maxReadDate 上次最大的检测时间
     * @return 列表
     */
    public List<MgParamLog> getMgParamLog(String sensorId, Date maxReadDate) {
        log.info("sensorId={}, maxReadDate={}, maxReadDateStr={}"
                ,  sensorId, maxReadDate, DateTime.of(maxReadDate).toString(DatePattern.NORM_DATETIME_PATTERN));
        MgParamLog queryParams = new MgParamLog();
        queryParams.setParentCode(sensorId);
        Map<String, Object> params = new HashMap<>();
        params.put("beginReadDate", maxReadDate);
        queryParams.setParams(params);

        return mgParamLogService.selectMgParamLogList(queryParams);
    }
}
